package com.devtools.framework.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.devtools.common.utils.DateUtils;
import com.devtools.common.utils.security.ShiroUtils;
import com.devtools.project.system.user.domain.User;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    // 新增的时候自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        LOGGER.info("自动填充创建时间和创建人字段 ....");
        if (this.getFieldValByName("createTime", metaObject) == null) {
            this.setFieldValByName("createTime", DateUtils.getNowDate(), metaObject);
        }
        if (this.getFieldValByName("updateTime", metaObject) == null) {
            this.setFieldValByName("updateTime", DateUtils.getNowDate(), metaObject);
        }
        User user = ShiroUtils.getSysUser();
        if (user != null) {
            this.setFieldValByName("createBy", user.getUserName(), metaObject);
            this.setFieldValByName("updateBy", user.getUserName(), metaObject);
        }
    }

    // 更新的税后自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        LOGGER.info("start update fill ....");
        this.setFieldValByName("updateTime", DateUtils.getNowDate(), metaObject);
        User user = ShiroUtils.getSysUser();
        if (user != null) {
            this.setFieldValByName("updateBy", user.getUserName(), metaObject);
        }
    }
}
